<template>
  <div class="chat-page page-container">
    <!-- 使用侧边栏组件 -->
    <chat-sidebar
      :is-open="isSidebarOpen"
      @close="toggleSidebar"
      @select-chat="handleSelectChat"
    />

    <div class="chat-container">
      <div class="chat-header">
        <h2>{{ appInfo.name }}</h2>
      </div>

      <div class="chat-messages" ref="messageContainer">
        <div class="welcome-message" v-if="messages.length === 0">
          <a-icon type="robot" class="robot-icon" />
          <h3>你好！我是{{ appInfo.name }}</h3>
          <p>我可以帮你完成各种任务，请告诉我你需要什么帮助？</p>
        </div>

        <div v-else class="message-list">
          <div
            v-for="(msg, index) in messages"
            :key="index"
            :class="['message-item', msg.type]"
          >
            <div class="message-avatar">
              <a-icon :type="appInfo.icon" />
            </div>
            <div class="message-content">
              <!-- 文本消息 -->
              <div v-if="msg.contentType === 'text'" class="text-content">
                {{ msg.content }}
              </div>

              <!-- 文件消息 -->
              <div v-else-if="msg.contentType === 'file'" class="file-content">
                <div class="file-info">
                  <a-icon :type="getFileIcon(msg.file.type)" />
                  <span class="file-name">{{ msg.file.name }}</span>
                  <span class="file-size"
                    >({{ formatFileSize(msg.file.size) }})</span
                  >
                </div>
                <!-- 如果是图片，显示预览 -->
                <div v-if="isImage(msg.file.type)" class="image-preview">
                  <img :src="msg.file.url" :alt="msg.file.name" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input-wrapper">
        <div class="input-toolbar">
          <div class="toolbar-left">
            <a-button
              type="link"
              icon="menu-unfold"
              :class="{ active: isSidebarOpen }"
              @click="toggleSidebar"
            />
            <a-upload
              :show-upload-list="false"
              :before-upload="handleFileUpload"
              accept=".txt,.doc,.docx,.pdf,.png,.jpg,.jpeg"
            >
              <a-button type="link" icon="paper-clip">
                <span class="upload-text">传递文件</span>
              </a-button>
            </a-upload>
          </div>
          <div class="toolbar-right">
            <span class="text-count" v-if="message"
              >{{ message.length }}/2000</span
            >
          </div>
        </div>
        <div class="chat-input">
          <a-textarea
            v-model="message"
            placeholder="输入你的问题，Shift + Enter 换行，Enter 发送..."
            :auto-size="{ minRows: 1, maxRows: 6 }"
            :maxLength="2000"
            @pressEnter.exact="sendMessage"
            @pressEnter.shift.exact="handleShiftEnter"
          />
          <a-button
            type="primary"
            @click="sendMessage"
            :disabled="!message.trim()"
            >发送</a-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Input, Button, Icon, Upload, message } from "ant-design-vue";
import ChatSidebar from "./ChatSidebar.vue";
import { execMessage,queryMessageList } from "@/api/cozeAi";
export default {
  name: "Chat",
  components: {
    "a-textarea": Input.TextArea,
    "a-button": Button,
    "a-icon": Icon,
    "a-upload": Upload,
    ChatSidebar,
  },
  data() {
    return {
      message: "",
      isSidebarOpen: false,
      currentChat: null,
      maxFileSize: 10 * 1024 * 1024, // 10MB
      messages: [], // 存储聊天消息
      appInfo: {
        id: null,
        icon: "robot",
        name: "AI助手",
        description: "一个智能的AI助手，可以回答你的问题，帮助你完成各种任务。",
        singlePrice: 0.1,
      },
      conversationId: "",
    };
  },
  created() {
    // 从路由参数获取应用信息
    const { id, name, icon, description, singlePrice, conversationId, chatId } =
      this.$route.query;
    if (id && name) {
      this.appInfo.id = id;
      this.conversationId = conversationId;
      this.appInfo.icon = icon;
      this.appInfo.name = name;
      this.appInfo.description = description;
      this.appInfo.singlePrice = singlePrice;

      // 添加欢迎消息
      this.messages.push({
        icon: icon,
        name: name,
        contentType: "text",
        type: "assistant",
        description: description,
        singlePrice: singlePrice + "积分/次",
        content: `你好！我是${name}，请问有什么可以帮你？`,
      });

      queryMessageList({
        chatId: chatId,
        projectId: this.appInfo.id,
        conversationId: this.conversationId
      }).then(res => {
        if(res.code === 200){
          res.data.data.forEach(item => {
            this.messages.push({
              icon: item.icon,
              name: item.name,
              contentType: "text",
              type: "assistant",
              content: item.content,
            });
          })
        }
      })
    }
  },
  methods: {
    toggleSidebar() {
      this.isSidebarOpen = !this.isSidebarOpen;
    },
    sendMessage() {
      if (!this.message.trim()) return;

      // 添加用户消息
      this.messages.push({
        icon: this.appInfo.icon,
        name: this.appInfo.name,
        type: "user",
        contentType: "text",
        content: this.message.trim(),
      });

      // this.messages.push({
      //   icon: this.appInfo.icon,
      // name: this.appInfo.name,
      // contentType: 'text',// 文本消息
      // type: 'assistant',// 标识AI回复的
      // content: `[${this.appInfo.name}] 我收到了你的消息，正在处理中...`,
      // });

      // 清空输入框
      // this.message = "";
      execMessage({
        projectId: this.appInfo.id,
        messageType: "text",
        message: this.message.trim(),
        conversationId: this.conversationId,
      }).then((res) => {
        
        if (res.code === 200) {
          res.data.data.forEach((item) => {
            if(item.type === 'answer'){
              this.messages.push({
                icon: this.appInfo.icon,
                name: this.appInfo.name,
                contentType: "text", // 文本消息
                type: "assistant", // 标识AI回复的
                content: item.content,
              });
            }
          });
          this.scrollToBottom();
        }
      }).finally(() => {
        this.message = '';
      });
      // 模拟AI回复
      // setTimeout(() => {
      //   this.messages.push({
      //     type: 'assistant',
      //     contentType: 'text',
      //     content: `[${this.appInfo.name}] 我收到了你的消息，正在处理中...`
      //   });
      //   this.scrollToBottom();
      // }, 500);
    },
    handleSelectChat(chat) {
      this.currentChat = chat;
      console.log("选择对话:", chat);
      // 在移动端自动关闭侧边栏
      if (window.innerWidth <= 768) {
        this.isSidebarOpen = false;
      }
    },
    handleShiftEnter(e) {
      // 阻止默认行为，允许换行
      e.preventDefault();
      const textArea = e.target;
      const start = textArea.selectionStart;
      const end = textArea.selectionEnd;
      this.message =
        this.message.substring(0, start) + "\n" + this.message.substring(end);
      // 设置光标位置
      this.$nextTick(() => {
        textArea.selectionStart = textArea.selectionEnd = start + 1;
      });
    },
    async handleFileUpload(file) {
      if (file.size > this.maxFileSize) {
        message.error("文件大小不能超过10MB");
        return false;
      }

      try {
        // 这里应该是真实的文件上传逻辑
        // 现在用模拟的URL代替
        const fileUrl = URL.createObjectURL(file);

        // 添加文件消息
        this.messages.push({
          type: "user",
          contentType: "file",
          file: {
            name: file.name,
            size: file.size,
            type: file.type,
            url: fileUrl,
          },
        });

        // 模拟AI回复
        // setTimeout(() => {
        //   this.messages.push({
        //     type: "assistant",
        //     contentType: "text",
        //     content: "我已收到你的文件，正在分析处理中...",
        //   });
        //   this.scrollToBottom();
        // }, 500);

        message.success("文件上传成功");
      } catch (error) {
        message.error("文件上传失败");
      }
      return false;
    },
    getFileIcon(fileType) {
      if (fileType.startsWith("image/")) return "picture";
      if (fileType.includes("pdf")) return "file-pdf";
      if (fileType.includes("word")) return "file-word";
      return "file";
    },
    formatFileSize(bytes) {
      if (bytes < 1024) return bytes + "B";
      if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + "KB";
      return (bytes / (1024 * 1024)).toFixed(1) + "MB";
    },
    isImage(fileType) {
      return fileType.startsWith("image/");
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messageContainer;
        container.scrollTop = container.scrollHeight;
      });
    },
  },
  watch: {
    // 监听路由参数变化
    "$route.query": {
      handler(newQuery) {
        const { appId, appName } = newQuery;
        if (appId && appName && appId !== this.appInfo.id) {
          this.appInfo.id = appId;
          this.appInfo.name = appName;
          // 清空之前的消息
          this.messages = [
            {
              type: "assistant",
              contentType: "text",
              type: "assistant", // 标识回复的
              content: `你好！我是${appName}，请问有什么可以帮你？`,
            },
          ];
        }
      },
      immediate: true,
    },
    messages: {
      handler() {
        this.scrollToBottom();
      },
      deep: true,
    },
  },
};
</script>

<style lang="less" scoped>
.chat-page {
  position: relative;
  padding: 0;
  background: #f5f7fa;
  height: 100%;
  overflow: hidden;

  .chat-container {
    height: 100%;
    margin-left: 0;
    transition: all 0.3s ease;
    display: flex;
    flex-direction: column;
    background: #fff;
  }

  .chat-header {
    padding: 16px 24px;
    background: #fff;
    border-bottom: 1px solid #f0f0f0;

    h2 {
      margin: 0;
      font-size: 18px;
      color: #333;
    }
  }

  .chat-messages {
    flex: 1;
    padding: 24px;
    overflow-y: auto;

    .message-list {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }

    .message-item {
      display: flex;
      gap: 12px;
      max-width: 80%;

      &.user {
        margin-left: auto;
        flex-direction: row-reverse;

        .message-content {
          background: #e6f7ff;
          border-radius: 12px 2px 12px 12px;
        }

        .message-avatar {
          background: #1890ff;

          .anticon {
            color: #fff;
          }
        }
      }

      &.assistant {
        margin-right: auto;

        .message-content {
          background: #f5f5f5;
          border-radius: 2px 12px 12px 12px;
        }

        .message-avatar {
          background: #e6f7ff;

          .anticon {
            color: #1890ff;
          }
        }
      }
    }

    .message-avatar {
      flex-shrink: 0;
      width: 40px;
      height: 40px;
      border-radius: 20px;
      display: flex;
      align-items: center;
      justify-content: center;

      .anticon {
        font-size: 20px;
      }
    }

    .message-content {
      padding: 12px 16px;
      font-size: 14px;
      line-height: 1.6;
      word-break: break-word;

      .text-content {
        white-space: pre-wrap;
      }

      .file-content {
        .file-info {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 8px;

          .anticon {
            font-size: 20px;
            color: #1890ff;
          }

          .file-name {
            font-weight: 500;
          }

          .file-size {
            color: #999;
            font-size: 12px;
          }
        }

        .image-preview {
          margin-top: 8px;
          max-width: 300px;

          img {
            width: 100%;
            border-radius: 4px;
          }
        }
      }
    }
  }

  .chat-input-wrapper {
    border-top: 1px solid #f0f0f0;
    background: #fff;

    .input-toolbar {
      padding: 8px 16px;
      border-bottom: 1px solid #f5f5f5;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .toolbar-left {
        display: flex;
        align-items: center;
        gap: 8px;

        .ant-btn {
          padding: 4px 8px;

          &.active {
            color: #1890ff;
            background: #e6f7ff;
          }
        }

        .upload-text {
          font-size: 14px;
          margin-left: 4px;
        }
      }

      .toolbar-right {
        .text-count {
          font-size: 12px;
          color: #999;
        }
      }
    }

    .chat-input {
      padding: 16px;
      display: flex;
      gap: 8px;
      align-items: flex-start;

      .ant-input {
        border-radius: 4px;
        resize: none;
        padding: 8px 12px;
        font-size: 14px;
        line-height: 1.6;

        &:focus {
          box-shadow: none;
          border-color: #40a9ff;
        }
      }

      .ant-btn {
        border-radius: 4px;
        height: 38px;
        padding: 0 24px;
        margin-top: 1px;

        &[disabled] {
          cursor: not-allowed;
          opacity: 0.6;
        }
      }
    }
  }
}

// 移动端适配
@media screen and (max-width: 768px) {
  .chat-messages {
    .message-item {
      max-width: 90%;
    }

    .message-content {
      .file-content {
        .image-preview {
          max-width: 200px;
        }
      }
    }
  }
}
</style>
